package com.liyu.rabbit.producer;

import cn.hutool.core.date.DateUtil;
import com.liyu.rabbit.consumer.Consumer;
import com.liyu.rabbit.factory.RabbitFactory;
import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author 李誉
 * @date 2022-07-02 22:12
 * @description
 */
public class Producer {

    public static final String DELAYED_EX = "delayed-ex";

    public static void main(String[] args) throws Exception{
        // 1、创建信道
        Channel newChannel = RabbitFactory.createNewChannel();

        // 2、 开启发布确认
        newChannel.confirmSelect();

        // 3、 发布成功监听函数
        String confirmString = "消息%s发布成功成功，发布时间：%s";
        ConfirmCallback callback = (deliveryTag, multiple) -> {
            System.out.println(String.format(confirmString, deliveryTag, DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
        };
        newChannel.addConfirmListener( callback, (deliveryTag, multiple)->{});

        // 4、设置延迟交换机
        Map<String, Object> arg = new HashMap<>(1);
        arg.put("x-delayed-type", BuiltinExchangeType.DIRECT.getType());
        newChannel.exchangeDeclare(DELAYED_EX, "x-delayed-message", false, false, arg);

        // 设置消息序列化参数
        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties("text/plain",
                null,
                null,
                2,
                0, null, null,
                null,
                null, null, null, null,
                null, null);
        Map<String, Object> headers = new HashMap<>(1);
        headers.put("x-delay", 10000);
        AMQP.BasicProperties.Builder builder = basicProperties.builder().headers(headers);

        Scanner scanner = new Scanner(System.in);
        String msg = null;
        System.out.println("请输入发送的消息");
        while (scanner.hasNext()) {
            msg = scanner.next();
            if (msg == null || "".equals(msg)) {
                continue;
            }
            newChannel.basicPublish( DELAYED_EX, Consumer.RK, builder.build(), msg.getBytes(StandardCharsets.UTF_8));
            System.out.println("请输入发送的消息");
        }

    }
}
